package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetTRresultType
 */
//@WebServlet(description = "取得測試結果代號與中文的對照", urlPatterns = { "/GetTRresultType" })
public class GetTRresultType extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetTRresultType() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT sn, value, name FROM tms_trresulttype";
		String returnResult = "";
		ArrayList<TrResultType> trResultTypes = new ArrayList<TrResultType>();
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			
			while (rs.next()) {
				TrResultType trResultType = new TrResultType();
				trResultType.setSn(rs.getInt("sn"));
				trResultType.setValue(rs.getString("value"));
				trResultType.setName(rs.getString("name"));
				trResultTypes.add(trResultType);
			}
			returnResult = new Gson().toJson(trResultTypes);
			returnResult = returnResult.substring(1, returnResult.length());
			returnResult = "{\"sqlData\":["+returnResult+",\"strSQL\":\""+strSQL+"\",\"size\":\""+trResultTypes.size()+"\"}";
		} catch (SQLException e) {
			returnResult = "{\"errorMsg\":\""+wid.keepErrorMes(conn, ps, e,"", true)+"\"}";
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = e.toString();
			}
		}
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
		
	}

}
